/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package barreirasacscomunicator;


import barreirasacscomunicator.connection.SshTunnels;
import barreirasacscomunicator.gui.ComunicatorGUI;
import barreirasacscomunicator.gui.Login;
import barreirasacscomunicator.gui.UpdateAvailable;
import barreirasacscomunicator.gui.Updater;
import barreirasacscomunicator.irc.MyIRCEventListener;
import java.awt.AWTException;
import java.awt.Image;
import java.awt.MenuItem;
import java.awt.PopupMenu;
import java.awt.SystemTray;
import java.awt.Toolkit;
import java.awt.TrayIcon;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import org.schwering.irc.lib.IRCConnection;

/**
 *
 * @author rjsantos
 */
public class BACSComunicator {

    private final String BACSC_VERSION="0.1.1";
    private final String NEWFILENAME="BarreirasACSComunicatorNew.jar";


    private ComunicatorGUI gui;
    private boolean guiVisible=false;
    private IRCConnection conn;
    private SshTunnels sshTunnels;


    public BACSComunicator(){


        

        putTray();

        checkUpdates();

        
    }

    public void startComunicator(){

        sshTunnels = new SshTunnels();
        sshTunnels.connect();

        gui = new ComunicatorGUI(this);
        gui.setVisible(guiVisible);

        Login login= new Login(this);
        login.setVisible(true);
    }

    public void checkUpdates() {
        //obter ficheiro version.txt do acs.barreiras.com.pt/Comunicator/version.txt
        //caso a versao seja diferente de BACSC_VERSION
        //  copiar o ficheiro de update e executalo

        String v="";
        
        try {

            //System.out.println("\n\n inicio do update \n\n");
            URL url = new URL("http://acs.barreiras.com.pt/Comunicator/version.txt");


            URLConnection urlC = url.openConnection();



            InputStream is = url.openStream();

            //BufferedInputStreamReader br;= new BufferedReader();


            byte[] text = new byte[255];
            int size = is.read(text);


            v=new String(text);
            v=v.substring(0, size);
            //System.out.println("v- version:"+v+ " len:"+ v.length() );
            //System.out.println("B- version:"+BACSC_VERSION+ " len:"+BACSC_VERSION.length());

            is.close();



            if(BACSC_VERSION.compareTo(v)!=0){

                UpdateAvailable update = new UpdateAvailable();
                update.setVisible(true);

                /*
                try{
                Updater updater= new Updater();
                URL url = new URL("http://acs.barreiras.com.pt/Comunicator/BarreirasACSComunicator.jar");
                URLConnection urlC = url.openConnection();
                InputStream is = url.openStream();
                FileOutputStream fos=null;
                fos = new FileOutputStream(NEWFILENAME);
                System.out.println("size:"+urlC.getContentLength());
                updater.setTotal(urlC.getContentLength());
                updater.setVisible(true);
                int oneChar, count=0;
                while ((oneChar=is.read()) != -1)
                {
                fos.write(oneChar);
                count++;
                //System.out.println("size:"+count);
                updater.setDone(count);
                }
                is.close();
                fos.close();
                File oldFile = new File("BarreirasACSComunicator.jar");
                File newFile = new File("BarreirasACSComunicator-"+BACSC_VERSION+".jar");
                boolean result = oldFile.renameTo(newFile);
                oldFile = new File(NEWFILENAME);
                newFile = new File("BarreirasACSComunicator.jar");
                newFile.delete();
                result = oldFile.renameTo(newFile);
                try {
                updater.wait();
                } catch (InterruptedException ex) {
                //Logger.getLogger(BACSComunicator.class.getName()).log(Level.SEVERE, null, ex);
                }
                } catch (MalformedURLException ex) {
                Logger.getLogger(BACSComunicator.class.getName()).log(Level.SEVERE, null, ex);
                }
                catch (IOException ex) {
                Logger.getLogger(BACSComunicator.class.getName()).log(Level.SEVERE, null, ex);
                }
                System.exit(0);
                 */

            }
            else{

            }


        } catch (MalformedURLException ex) {
            //System.out.println("\n\n ex \n\n");
            Logger.getLogger(BACSComunicator.class.getName()).log(Level.SEVERE, null, ex);
        }
        catch (IOException ex) {
            //System.out.println("\n\n ex \n\n");
            Logger.getLogger(BACSComunicator.class.getName()).log(Level.SEVERE, null, ex);
        }





        
     this.startComunicator();
     
     //System.out.println("\n\n fim  do update \n\n");


       
    }


    public void login(String user,String pass){

              conn = new IRCConnection(
                            "127.0.0.1",
                            6667,
                            6669,
                            pass,
                            user,
                            "Foobar",
                            "foobarcom"
                          );


        conn.addIRCEventListener(new MyIRCEventListener(gui));
        conn.setDaemon(true);
        conn.setColors(false);
        conn.setPong(true);


         try {
           conn.connect(); // Try to connect!!! Don't forget this!!!
           conn.doJoin("#BarreirasACS");
           conn.doJoin("#BarreirasACSToques");
           //doPrivmsg(java.lang.String target, java.lang.String msg)

         } catch (IOException ioexc) {
           ioexc.printStackTrace();
         }

    }



    public void sendMessage(String msg){
        conn.doPrivmsg("#BarreirasACS", msg);
    }


    public void sendToques(){
        conn.doPrivmsg("#BarreirasACSToques", "SendToque");
    }

    public void getUsers(){
        conn.doNames("#BarreirasACS");
    }

    public void showWindow(){

        guiVisible=true;
        gui.setVisible(guiVisible);
    }

    public void putTray(){

        final TrayIcon trayIcon;



        if (SystemTray.isSupported()) {

            SystemTray tray = SystemTray.getSystemTray();
            Image image = Toolkit.getDefaultToolkit().getImage("resources/asww.png");



            MouseListener mouseListener = new MouseListener() {

                public void mouseClicked(MouseEvent e) {
                    //System.out.println("Tray Icon - Mouse clicked!");
                }

                public void mouseEntered(MouseEvent e) {
                    //System.out.println("Tray Icon - Mouse entered!");
                }

                public void mouseExited(MouseEvent e) {
                    //System.out.println("Tray Icon - Mouse exited!");
                }

                public void mousePressed(MouseEvent e) {
                    //System.out.println("Tray Icon - Mouse pressed!");
                }

                public void mouseReleased(MouseEvent e) {
                    //System.out.println("Tray Icon - Mouse released!");
                }
            };

            ActionListener exitListener = new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    //System.out.println("Exiting...");
                    System.exit(0);
                }
            };

            PopupMenu popup = new PopupMenu();
            MenuItem defaultItem = new MenuItem("Exit");
            defaultItem.addActionListener(exitListener);
            popup.add(defaultItem);

            trayIcon = new TrayIcon(image, "Tray Demo", popup);

            ActionListener actionListener = new ActionListener() {
                public void actionPerformed(ActionEvent e) {


                    if(!guiVisible){
                        guiVisible=true;
                    }else{
                        guiVisible=false;
                    }
                    gui.setVisible(guiVisible);
                    //trayIcon.displayMessage("Action Event",
                   //     "An Action Event Has Been Performed!",
                   //     TrayIcon.MessageType.INFO);
                }
            };

            trayIcon.setImageAutoSize(true);
            trayIcon.addActionListener(actionListener);
            trayIcon.addMouseListener(mouseListener);

            try {
                tray.add(trayIcon);
            } catch (AWTException e) {
                System.err.println("TrayIcon could not be added.");
            }

        } else {

            //  System Tray is not supported

        }





    }

}
